<?php
/**
 * Created by 链行天下.
 * User: tangjianing(990921093@qq.com)
 * Date: 2019/2/1 10:40
 */

namespace App\Tools;

use StephenHill\Base58;

class VerifyWalletAddress2
{
    const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

    public static function verify($walletAddress, $prefix)
    {
        $prefixLen = strlen($prefix);
        //校验前缀
        if (!self::checkPrefix($walletAddress)) {
            return false;
        };
        //切除前缀
        $newWalletAddress = substr($walletAddress, $prefixLen);
        //base58解码
        $base58 = new Base58(self::ALPHABET);
        $base58_decode =  $base58->decode($newWalletAddress);
        //$base58_decode =  self::base58_decode($newWalletAddress);
        //去掉最后的4个字节
        $string = substr($base58_decode , 0, -4);
        //取出最后4个字节
        $end_string = substr($base58_decode , -4);
        //ripemd160 hash
        $hash = hash('ripemd160', $string, true);
        //ripemd160之后取出前4位字节
        $hash_string = substr($hash , 0,4);
        return $end_string != $hash_string ? false : true;
    }

    protected static function checkPrefix($walletAddress)
    {
        return strpos($walletAddress, 'bcb') !== 0 ? false : true;
    }
}
